﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OBB {
	private float halfW;
	private float halfH;

	public GameObject go;

	public Vector3 pos { set; get; }
	public Vector3 vX { set; get; }
	public Vector3 vY { set; get; }
	public float addAngle { set; get; }

	public OBB(GameObject go)
    {
		this.go = go;
		Transform transform = go.transform;
		this.pos = transform.position;
		this.halfW = transform.localScale.x / 2.0f;
		this.halfH = transform.localScale.y / 2.0f;
		UpdateGo();
    }

	public void UpdateGo()
    {
		this.vectorXY();
    }

	private void vectorXY()
    {
		float angle = this.go.transform.localEulerAngles.z;
		double rot = angle * Math.PI / 180f;
		this.vX = new Vector3((float)Math.Cos(rot), (float)Math.Sin(rot), 0);
		this.vY = new Vector3((float)-Math.Sin(rot), (float)Math.Cos(rot), 0);
	}

	private float shaftLength(Vector3 vShaft)
    {
		return this.halfW * Math.Abs(Vector3.Dot(this.vX, vShaft)) + this.halfH * Math.Abs(Vector3.Dot(this.vY, vShaft));
	}

	public bool Check(OBB obb)
    {
		Vector3 dis = this.pos - obb.pos;
		if(this.shaftLength(obb.vX) + obb.shaftLength(obb.vX) <= Math.Abs(Vector3.Dot(dis, obb.vX))) { return false; }
		if(this.shaftLength(obb.vY) + obb.shaftLength(obb.vY) <= Math.Abs(Vector3.Dot(dis, obb.vY))) { return false; }
		if(this.shaftLength(this.vX) + obb.shaftLength(this.vX) <= Math.Abs(Vector3.Dot(dis, this.vX))) { return false; }
		if(this.shaftLength(this.vY) + obb.shaftLength(this.vY) <= Math.Abs(Vector3.Dot(dis, this.vY))) { return false; }

		return true;
    }

}
